﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcShoppingMall.Model;
using MvcShoppingMall.HtmlHelper;
using MvcShoppingMall.Models;

namespace MvcShoppingMall.Controllers
{
    /// <summary>
    /// 商城主页面
    /// </summary>
    public class HomeController : BaseController
    {
        ShoppingMallEntities storeDB = new ShoppingMallEntities();
        //购物车的标识
        string ShoppingCartId { get; set; }

        //用于在Seesion中保存当前用户的购物车标识
        public const string CartSessionKey = "CartId";

        #region 商城首页
        public ActionResult Index()
        {
            //查询商品信息
            var shoppList = dbContext.wst_goods.ToList().Take(6);
            ViewBag.shopList = shoppList;
            return View();
        }
        #endregion

        #region 商品详情
        public ActionResult GoodsDatails(int gid)
        {
            var goodsList = dbContext.wst_goods.Where(g => g.goodsId == gid).ToList();
            ViewBag.goods = goodsList[0];
            int shopId = goodsList[0].shopId;
            var shoplist = dbContext.wst_shops.Where(s => s.shopId == shopId).ToList();
            ViewBag.ShopList = shoplist[0];
            Goods_img(gid);
            Wst_Goods(gid);
            ListGoods(shopId);
            ListColor(gid);
            Listsize(gid);
            ListApprises(gid);
            return View();
        }
        public ActionResult InsertBycard(string color, string size, string count, Cart car)
        {
            string data = "no";
            //var car = dbContext.Carts.Find();
            car.Count = Int32.Parse(count);
            car.goodsId = 6;
            car.Colorid = Int32.Parse(color);
            car.Sizeid = Int32.Parse(size);
            car.DateCreate = DateTime.Now;
            car.UserId = 1;
            car.RecordId = 2333;
            car.SpwceId = 1;
            dbContext.Carts.Add(car);
            dbContext.SaveChanges();
            data = "ok";
            return Content(data);
        }
        private void add(int goodid, int shopid, Cart cart)
        {
            cart.SpwceId = shopid;
            cart.goodsId = goodid;
        }
        private void Goods_img(int id)
        {
            //获取图片表信息
            List<goods_images> img = (from g in dbContext.goods_images
                                      where g.goodsId == id
                                      select g).ToList();
            ViewBag.img = img;
        }

        private void Wst_Goods(int id)
        {
            var goods = dbContext.wst_goods.Find(id);
            ViewBag.goods = goods as wst_goods;
        }
        private void ListColor(int id)
        {
            List<GoodsColor> color = (from g in dbContext.GoodsColors
                                      where g.GoodsId == id
                                      select g).ToList();
            ViewBag.color = color;
        }
        private void Listsize(int id)
        {
            List<GoodsSize> size = (from g in dbContext.GoodsSizes
                                    where g.GoodsId == id
                                    select g).ToList();
            ViewBag.size = size;
        }
        private void ListApprises(int id)
        {
            List<wst_goods_appraises> Apprises = (from g in dbContext.wst_goods_appraises
                                                  where g.goodsId == id
                                                  select g).ToList();
            List<string> userName = new List<string>();
            List<string> userimage = new List<string>();
            List<string> ddcolor = new List<string>();
            List<string> ddsize = new List<string>();
            foreach (var info in Apprises)
            {
                var users = dbContext.wst_users.Find(info.userId);
                var color = dbContext.GoodsColors.Find(info.Colorid);
                var size = dbContext.GoodsSizes.Find(info.Sizeid);
                ddcolor.Add(color.ColorName);
                ddsize.Add(size.SizeName);
                userName.Add(users.userName);
                userimage.Add(users.userImage);
            }
            ViewBag.ddcolor = ddcolor;
            ViewBag.ddsize = ddsize;
            ViewBag.userName = userName;
            ViewBag.userimage = userimage;
            ViewBag.Apprises = Apprises;
        }
        private void ListGoods(int id)
        {
            //获取商品对象集合  
            List<wst_goods> good = dbContext.wst_goods.Where(g => g.shopId == id).ToList();
            //商品对象
            ViewBag.shopgood = good;
        }
        #endregion

        #region 个人注册
        public ActionResult Register()
        {
            return View();
        }

        public ActionResult ZcRegister(MvcShoppingMall.Model.wst_users user)
        {

            try
            {
                string flag = "false";
                user.dataFlag = 1;
                user.userStatus = 1;
                user.userImage = "false";
                user.userType = 1;
                user.createTime = DateTime.Now;
                dbContext.wst_users.Add(user);
                if (dbContext.SaveChanges() > 0)
                {
                    //一旦成功注册，也需要成功注册购车
                    this.MigrateShoppingCart(user.loginName);
                    flag = "true";
                }
                return Content(flag);
            }
            catch (Exception e)
            {
                throw e;
            }

        }

        #endregion

        #region 申请入驻
        public ActionResult Enter()
        {

            return View();
        }
        #endregion

        #region 个人登录
        public ActionResult UserLogin()
        {
            return View();
        }
        [HttpPost]
        public ActionResult DoUserLogin(string loginName, string loginPwd)
        {
            try
            {
                string mes = "false";
                var user = dbContext.wst_users.Where(u => u.loginName == loginName.Trim() && u.loginPwd == loginPwd.Trim()).FirstOrDefault();

                if (user != null)
                {
                    this.MigrateShoppingCart(user.loginName);
                    Session["user"] = user;
                    mes = "true";
                }
                return Content(mes);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        #endregion

        #region 搜索结果展示(列表式)
        public ActionResult SearchResult(string txtSearch, int pageIndex = 1, int pageSize = 3)
        {
            //EF数据源
            var good = dbContext.wst_goods.ToList();
            //计算总条数
            int totalCount = good.Count;

            List<wst_goods> listgood = new List<wst_goods>();
            foreach (var item in good)
            {
                if (item.goodBrands.Contains(txtSearch) || item.goodsName.Contains(txtSearch))
                {
                    listgood.Add(item);
                }
            }

            ViewBag.seachGoods = listgood;

            //分页数据
            var wst_goodsList = listgood.OrderBy(m => m.goodsId).Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList();
            ViewBag.PageList = wst_goodsList;

            //获取页面索引
            int PageIndex = string.IsNullOrEmpty(Request.QueryString["pageIndex"]) ? 1
                            : Convert.ToInt32(Request.QueryString["pageIndex"]);
            //设置总页数
            int totalPage = listgood.Count() % pageSize != 0 ? listgood.Count() / pageSize + 1
                                                                    : listgood.Count() / pageSize;
            //实例化分页类，通过数据源、当前页索引、页面大小获取该页数据  
            PageList<wst_goods> pagelist = new PageList<wst_goods>(listgood, pageIndex, pageSize, ref totalCount, ref totalPage);
            //记录是否有上一页
            ViewBag.IsUpPage = pagelist.HasPreviousPage;
            //计算上一页索引
            ViewBag.upPage = pagelist.PageIndex - 1 == 0 ? 1 : pagelist.PageIndex - 1;
            //记录是否有下一页
            ViewBag.IsNextPage = pagelist.HasNextPage;
            //计算下一页索引
            ViewBag.nextPage = pagelist.TotalPage < pagelist.PageIndex + 1 ? pagelist.TotalPage : pagelist.PageIndex + 1;

            return View(pagelist);
        }
        #endregion

        #region
        //[HttpPost]
        //public ActionResult SearchResult(string txtSearch,int pageIndex = 1, int pageSize = 3)
        //{
        //    //获取总条数
        //    //int totalCount = dbContext.wst_goods.Count();
        //    //EF数据源(from g in dbContext.wst_goods.OrderBy(m => m.goodsId).Skip(pageSize * (pageIndex - 1)).Take(pageSize)
        //                            //join s in dbContext.wst_shops
        //                            //on g.shopId equals s.shopId
        //                            //where g.goodBrands.Contains(txtSearch) || g.goodsName.Contains(txtSearch)
        //                            //select g).ToList();

        //    //EF数据源
        //    var good = dbContext.wst_goods.ToList();
        //    //计算总条数
        //    int totalCount = good.Count;

        //    List<wst_goods> listgood = new List<wst_goods>();
        //    foreach (var item in good)
        //    {
        //        if (item.goodBrands.Contains(txtSearch)||item.goodsName.Contains(txtSearch))
        //        {
        //            listgood.Add(item);
        //        }
        //    }

        //    ViewBag.seachGoods = listgood;

        //    //分页数据
        //    var wst_goodsList = listgood.OrderBy(m => m.goodsId).Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList();
        //    ViewBag.PageList = wst_goodsList;

        //    //获取页面索引
        //    int PageIndex = string.IsNullOrEmpty(Request.QueryString["pageIndex"]) ? 1
        //                    : Convert.ToInt32(Request.QueryString["pageIndex"]);
        //    //设置总页数
        //    int totalPage = listgood.Count() % pageSize != 0 ? listgood.Count() / pageSize + 1
        //                                                            : listgood.Count() / pageSize;

        //    //实例化分页类，通过数据源、当前页索引、页面大小获取该页数据  
        //    PageList<wst_goods> pagelist = new PageList<wst_goods>(listgood, pageIndex, pageSize, ref totalCount, ref totalPage);
        //    //记录是否有上一页
        //    ViewBag.IsUpPage = pagelist.HasPreviousPage;
        //    //计算上一页索引
        //    ViewBag.upPage = pagelist.PageIndex - 1 == 0 ? 1 : pagelist.PageIndex - 1;
        //    //记录是否有下一页
        //    ViewBag.IsNextPage = pagelist.HasNextPage;
        //    //计算下一页索引
        //    ViewBag.nextPage = pagelist.TotalPage < pagelist.PageIndex + 1 ? pagelist.TotalPage : pagelist.PageIndex + 1;

        //    return View(pagelist);

        //}
        #endregion

        #region 加入购物车
        public ActionResult AddShopCar(int id)
        {
            // 从数据库中检索商品
            var addedwst_goods = storeDB.wst_goods
            .Single(wst_goods => wst_goods.goodsId == id);
            // 把它添加到购物车
            var cart = ShoppingCart.GetCart(this.HttpContext);
            cart.AddToCart(addedwst_goods);
            // 返回主商店页面购买更多商品
            return RedirectToAction("Home/GoodsDatails");
        }
        #endregion

        #region 购物车、结算
        public ActionResult ShoppingCar()
        {
            //var cart = ShoppingCart.GetCart(this.HttpContext);
            //// 设置我们的视图模型
            //var viewModel = new ShoppingCartViewModel
            //{
            //    CartItems = cart.GetCartItems(),
            //    CartTotal = cart.GetTotal()
            //};
            var select = dbContext.Carts.ToList();
            ViewBag.delect = select;

            // 返回视图
            return View();
        }
           //删除购车商品
        [HttpPost]
        public ActionResult DeleShoppinCar(int id)
        {
            ShoppingCart cc = new Models.ShoppingCart();
            int result = cc.RemoveFromCart(id);
            if (result > 0)
            {
                return Content("OK");
            }
            return Content("NO");
        }
        #endregion

        [ChildActionOnly]
        public ActionResult CartSummary()
        {
            var cart = ShoppingCart.GetCart(this.HttpContext);
            ViewData["CartCount"] = cart.GetCount();
            return PartialView("CartSummary");
        }
       

        #region 确认订单，提交结算（核对登录状态才可进入此页面）
        //检查用户是否登录
        //
        // GET: /Checkout/AddressAndPayment
        //用来显示一个用户输入信息的表单
        public ActionResult ShopClear()
        {
            var user = Session["user"];
            if (user != null)
            {
                return View();

            }
            else
            {
                return RedirectToAction("UserLogin", "Home");
            }
        }

        [HttpPost]
        //验证用户的输入，处理订单
        public ActionResult AddressAndPayment(FormCollection values)
        {
            //订单是一个对象
            var order = new order();
            //通过模型绑定，将请求参数绑定在模型对象上
            TryUpdateModel(order);
            try
            {
                //生成订单
                order.userName = User.Identity.Name;
                order.createTime = DateTime.Now;
                //保存订单
                //保存之后，可以获得订单的编号
                //通过编号保存订单明细
                storeDB.orders.Add(order);
                storeDB.SaveChanges();
                //保存订单明细
                var cart = ShoppingCart.GetCart(this.HttpContext);
                cart.CreateOrder(order);
                return RedirectToAction("Complete", new { id = order.OrderId });
            }

            catch
            {
                //Invalid - redisplay with errors
                return View(order);
            }
        }
        #endregion

        #region 城市切换
        public ActionResult CityCut()
        {

            return View();
        }
        #endregion

        private void MigrateShoppingCart(string UserName)
        {
            // 取得购物车
            var cart = ShoppingCart.GetCart(this.HttpContext);
            cart.MigrateCart(UserName);
            //保存当前用户名称
            Session[ShoppingCart.CartSessionKey] = UserName;
        }
        //
        // GET: /Checkout/Complete
        //完成订单之后的提示
        public ActionResult Complete(int id)
        {

            bool isValid = storeDB.orders.Any(
            o => o.OrderId == id &&
            o.userName == User.Identity.Name);
            if (isValid)
            {
                return View(id);
            }
            else
            {
                return View("Error");
            }
        }
    }
    
}
